<?php

class GoalsController extends Zend_Controller_Action
{

    public function init()
    {
        $this->locationsTable = new Application_Model_DbTable_Locations();
    }

    public function indexAction()
    {
        $this->_redirect('/goals/locations');
    }

    public function locationsAction()
    {
        $resultsPerPage = 15;
        $page = $this->_getParam('page');
        $type = $this->_getParam('type');
        if(!isset($page))
        { $page = 0; }
        $select = $this->locationsTable->select()
                                       ->where("found = 0")
                                       ->limitPage($page, $resultsPerPage);
        if(isset($type))
        { $select->where('type = ?', $type); }
        $this->view->locations = $select->query();
        $this->view->numberofpages = $this->countPages($resultsPerPage, $type);
        $this->view->locationsfound = $this->locationsTable->fetchAll("found = 1");
    }

    public function processlocationsAction()
    {
        $checkedlocations = $this->_getParam('checkedlocations');      
        if(isset($checkedlocations))
        {
            foreach($checkedlocations as $locationid)
            {
                $data = array('found' => 1);
                $this->locationsTable->update($data, "id = $locationid");
            }
        }
        $this->_redirect('/goals/locations');
    }

    public function processfiltersAction()
    {
        $this->_redirect("/goals/locations?");
    }

    private function countPages($resultsPerPage, $type)
    {
        $db = $this->locationsTable->getAdapter();
        $query = $db->select()
                    ->from('locations','count(*)')
                    ->where("found = 0")
                    ->where('type = ?', $type);
        $numRows = $db->fetchOne($query);
        $pages = ceil($numRows / $resultsPerPage);
        return $pages;
    }
}

